<template>
  <el-dialog
    :model-value="visible"
    :title="props.addNodeTitle"
    width="50%"
    @close="handleClose"
  >
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
      :rules="rules"
      status-icon
    >
      <el-form-item label="环节名称" prop="nodeName">
        <el-input v-model="ruleForm.nodeName" placeholder="请输入环节名称" />
      </el-form-item>
      <el-form-item label="环节说明" prop="remark">
        <el-input v-model="ruleForm.remark" placeholder="请输入环节名称" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="submitNode">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script>
export default { name: 'approvalDialog' }
</script>

<script setup>
import { ref, toRefs, reactive, onMounted, watch, defineProps, defineEmits, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus'

const props = defineProps({
  addNodeTitle: {
    type: String,
    default: "审核"
  },
  visible: {
    type: Boolean,
    default: false
  },
  nodeForm: {
    type: Object,
    default: {}
  },
})

const emits = defineEmits(['update:visible', 'addNodeChange'])

let { visible } = toRefs(props)

const handleClose = () => {
  ruleFormRef.value.resetFields()
  // 触发自定义事件来通知父组件关闭弹窗
  emits('update:visible', false)
}

const ruleFormRef = ref(null)
const ruleForm = ref({
  nodeName: "",
  remark: "",
})
const rules = ref({
  nodeName: [
    { required: true, message: '请输入节点名称', trigger: 'blur' }
  ],
  remark: [
    { required: true, message: '请输入节点说明', trigger: 'blur' }
  ],
})

const openDialog = async () => {
  nextTick(() => {
    if(props.nodeForm.nodeName) {
      ruleForm.value.nodeName = props.nodeForm.nodeName
      ruleForm.value.remark = props.nodeForm.remark
    }
  })
}

defineExpose({
  openDialog,
});


const submitNode = () => {
  ruleFormRef.value.validate((valid, fields) => {
    if(valid) {
      emits('addNodeChange', ruleForm.value)
      emits('update:visible', false)
      setTimeout(() => {
        ruleFormRef.value.resetFields()
      }, 500)
    } else {
      ElMessage.warning("请先完成必填项")
    }
  })
}
</script>

<style lang='scss' scoped></style>